class HomeController < ApplicationController
 
  before_filter :login_required
  
  #Declare struc
  ComputerByStartDate = Struct.new(:status, :count)
  ComputerCountByOs = Struct.new(:os, :count)
  
  def index
    @title="Dashboard"
    @companies = Company.all
    @rooms = Room.find(:all)
    @networks = Network.find(:all)
    @allComputers = Computer.find(:all)
    
    @computers = []
    for computer in Computer.all
      if (computer.room_id == nil) 
        @computers << computer
      end
    end
  	
  	@operation_counts_date = Operation.find(:all, :select => "count(*) as count,start_date", :group => "start_date")
    @operation_counts_status = Operation.find(:all, :select => "count(*) as count,status", :group => "status")
    
    @computers_counts = Computer.count(:group => "status").collect do |status, count|
      ComputerByStartDate.new(status, count)
    end
  	
  	@computer_os_counts = Computer.count( :group => "os" ).collect do |os, count|
    	ComputerCountByOs.new(os, count)
  	end
  end
  
  def update_tabs
    @companies = Company.all
    @rooms = Room.find(:all)
    @networks = Network.find(:all)
    @allComputers = Computer.find(:all)
    
    @computers = []
    for computer in Computer.all
      if (computer.room_id == nil) 
        @computers << computer
      end
    end
    
    for computer in @allComputers
      if (computer.status != 2)
        if (ComputersHelper::pingecho(computer.ip_address))
          computer.status = 1
        else
          computer.status = 0
        end
        computer.save
      end
    end
    
    @operation_counts_date = Operation.find(:all, :select => "count(*) as count,start_date", :group => "start_date")
    @operation_counts_status = Operation.find(:all, :select => "count(*) as count,status", :group => "status")
    
    @computers_counts = Computer.count(:group => "status").collect do |status, count|
      ComputerByStartDate.new(status, count)
    end
    
    @computer_os_counts = Computer.count( :group => "os" ).collect do |os, count|
      ComputerCountByOs.new(os, count)
    end
    render :update do |page|
      page.replace_html "overview_panel",:partial => 'layouts/lateral_panel'
      page.replace_html "roomRightId", :partial => 'supervisions/company_room_computer', :locals => {:companies => @companies}
      page.replace_html "operation_graph", :partial => 'supervisions/operation_report', :locals => {:operation_counts => @operation_counts}
      page.replace_html "computer_graph", :partial => 'supervisions/computer_report', :locals => {:computers_counts => @computers_counts}
      page.replace_html "os_graph", :partial => 'supervisions/os_report', :locals => {:computer_os_counts => @computer_os_counts}
    end
  end

end
